import logging

from django import forms
from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.views import generic
from django.views.decorators.cache import cache_page

from .models import Person as PersonModel

# from django.template import loader

#日志配置
LOG_FORMAT = "%(asctime)s %(name)s %(levelname)s %(pathname)s %(message)s "  # 配置输出日志格式
DATE_FORMAT = '%Y-%m-%d  %H:%M:%S %a '  # 配置输出时间的格式，注意月份和天数不要搞乱了
logger=logging.getLogger('myapp')

# -----------------------------------------------通用视图-------------------------------------
class PersonOne(generic.DetailView):
    model = PersonModel
    template_name = "myapp/person_detail.html"

class PersonList(generic.ListView):
    model = PersonModel
    context_object_name = 'persons'
    template_name = 'myapp/person_list.html'

    def get_queryset(self):
        '''获取用户列表'''
        return self.model.objects.all()

@cache_page(60 * 2)
def index(request):
    persons=PersonModel.objects.order_by('create_time')
    # tmp=loader.get_template('myapp/index.html')
    params={
        'persons':persons
    }

    # 日志
    # logger.basicConfig(level=logging.DEBUG,
    #                     format=LOG_FORMAT,
    #                     datefmt=DATE_FORMAT,
    #                     filename=r"myapp.log"  # 有了filename参数就不会直接输出显示到控制台，而是直接写入文件
    #                     )
    logger.debug("msg1")
    logger.info("msg2")
    logger.warning("msg3")
    logger.error("msg4")
    logger.critical("msg5")


    # 模拟错误，验证中间件的process_exception的功能
    # int('aaa')

    # return HttpResponse(tmp.render(params,request))
    # 简洁的方式
    return render(request,'myapp/index.html',params)

def persons(request):
    persons=PersonModel.objects.all()
    return render(request,'myapp/person_list.html',{'persons':persons})

def searchPerson(request):
    name=request.POST['pname']
    age=0
    if (request.POST['page'] !=""):
        age=int(request.POST['page'])
    result=None
    persons=PersonModel.objects.filter(name__icontains=name,age=age)
    result= render(request,'myapp/person_list.html',{'persons':persons})
    return result

def getPerson(request,pid):
    person=get_object_or_404(PersonModel,pk=pid)
    return render(request,'myapp/person_detail.html',{'person':person})
    # try:
    #     person=Person.objects.get(pk=pid)
    # except Person.DoesNotExist:
    #     raise Http404("用户未找到")
    # return HttpResponse(person)

# --------------------------------------------------django 的Form的使用--------------------------------------
class regForm(forms.Form):
    name=forms.CharField(label="用户名",error_messages={'required':"用户名不能为空"},required=True)
    pwd=forms.CharField(label="密码")
    error_messages = {
        'name': {'required': "用户名不能为空", },
        'age': {'required': "年龄不能为空", },
    }

def register(request):
    form_obj=regForm()
    if request.method=="POST":
        form_obj=regForm(request.POST)
        if form_obj.is_valid():
            return HttpResponse("注册成功！")

    return render(request,'myapp/regist.html',{"form_obj":form_obj})

# -------------------------------------------django 的ModelForm的使用-------------------------------------------
class PersonModelForm(forms.ModelForm):

    class Meta:
        model=PersonModel
        fields = "__all__"
        labels = {
            "name": "姓名",
            "age": "年龄",
            "create_time":"创建时间",
        }
        widgets = {
            # "password": forms.widgets.PasswordInput(attrs={"class": "c1"}),
            "create_time": forms.widgets.DateInput(attrs={"type": "date"}),
        }
        error_messages = {
            'name': {'required': "用户名不能为空", },
            'age': {'required': "年龄不能为空", },
        }

def personForm(request):
    person_form=PersonModelForm()

    if request.method=="POST":
        person_form=PersonModelForm(request.POST)
        if person_form.is_valid():
            person_form.save()
            return HttpResponse("保存成功")

    return render(request,"myapp/person_form.html",{"form":person_form})